from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.core.files.storage import FileSystemStorage
import os
from django.conf import settings
from rest_framework import generics, status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from. import serializers
from.models import Doctor, ConsultRecord
from.permissions import CanAddDoctorPermission
from rest_framework.generics import ListCreateAPIView


from rest_framework.views import APIView

class TestPermissionView(APIView):
    permission_classes = [CanAddDoctorPermission]

    def get(self, request):
        return Response({"message": "权限测试成功"})
@csrf_exempt
def upload_avatar(request):
    if request.method == 'POST':
        file = request.FILES.get('avatar')
        if file:
            fs = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'doctor_avatars'))
            try:
                filename = fs.save(file.name, file)
                url = settings.MEDIA_URL + 'doctor_avatars/' + filename
                return JsonResponse({'url': url})
            except Exception as e:
                print(f"文件保存出错: {e}")  # 添加这行调试语句
                return JsonResponse({'error': '上传失败'}, status=400)
    return JsonResponse({'error': '上传失败'}, status=400)
# 院内医生相关视图
# 获取院内医生列表并支持筛选，创建院内医生
class InHospitalDoctorListCreateView(ListCreateAPIView):
    queryset = Doctor.objects.all()
    serializer_class = serializers.DoctorSerializer
    permission_classes = [IsAuthenticated, CanAddDoctorPermission]

    def get_queryset(self):
        queryset = super().get_queryset()
        # 按科室筛选
        department = self.request.query_params.get('department')
        if department:
            queryset = queryset.filter(department=department)
        # 按医生姓名模糊搜索
        name = self.request.query_params.get('name')
        if name:
            queryset = queryset.filter(name__icontains=name)
        return queryset

    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 获取、更新、删除单个院内医生信息
class InHospitalDoctorRetrieveUpdateDestroyView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Doctor.objects.all()
    serializer_class = serializers.DoctorSerializer
    permission_classes = [IsAuthenticated]

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)


# 远程会诊医生相关视图
# 获取远程会诊医生列表并支持多条件筛选
class RemoteConsultDoctorListView(generics.ListAPIView):
    queryset = Doctor.objects.all()
    serializer_class = serializers.DoctorSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        queryset = super().get_queryset()
        specialty = self.request.query_params.get('specialty')
        title = self.request.query_params.get('title')
        name = self.request.query_params.get('name')

        if specialty:
            queryset = queryset.filter(specialty=specialty)
        if title:
            queryset = queryset.filter(title=title)
        if name:
            queryset = queryset.filter(name__icontains=name)
        return queryset


# 申请会诊（这里简单处理为保存会诊记录，可根据实际业务补充）
class ApplyConsultView(generics.CreateAPIView):
    queryset = ConsultRecord.objects.all()
    serializer_class = serializers.ConsultRecordSerializer
    permission_classes = [IsAuthenticated]


# 获取会诊记录列表
class ConsultRecordListView(generics.ListAPIView):
    queryset = ConsultRecord.objects.filter(status__in=['初步会诊', '辅助检查', '详细问诊'])  # 假设这些是结束状态，可调整
    serializer_class = serializers.ConsultRecordSerializer
    permission_classes = [IsAuthenticated]


# 获取、更新单个会诊记录
class ConsultRecordRetrieveUpdateView(generics.RetrieveUpdateAPIView):
    queryset = ConsultRecord.objects.all()
    serializer_class = serializers.ConsultRecordSerializer
    permission_classes = [IsAuthenticated]